﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EmployeeApp.Web.EmployeeService;
using EmployeeApp.Web.Mapper.Employee;
using EmployeeApp.Web.Models.Employee;

namespace EmployeeApp.Web.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ListEmployee()
        {
            ListEmployeeModel model = new ListEmployeeModel();      
            SetupRegisterViewModel(model);
            if (Request.QueryString["Sort"] != null)
            {
                GetAllResponseModel temp = Search(new GetAllRequestModel()
                {
                    EmpId = "",
                    Name = "",
                    Status = 0,
                    Sort = "EmpId",
                    SortType = sType.ASC
                });
                model.ListOfEmployee = temp.EmpList;
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult ListEmployee(string submitButton, string[] checkbox, ListEmployeeModel input)
        {
            if (ModelState.IsValid)
            {
               switch(submitButton) {
                   case "Search" :
                        input.ListOfEmployee = PrepareSearch(input);                      
                        break;
                   case "Delete" :
                        input = Delete(checkbox, input);
                        break;
                   default :
                        break;
               }
            }
            SetupRegisterViewModel(input);
            return View(input);
            
        }

        public ActionResult ViewDetail(String EmpId)
        {
            EmployeeService.EmployeeServiceClient service = new EmployeeService.EmployeeServiceClient();

            GetAllRequest objGet = new GetAllRequest(new GetAllRequestDto
            {
                EmpId = EmpId
            });

            EmployeeService.GetAllResponse list = service.GetAll(objGet);
            EmployeeModel resultModel = null;


            if (list.GetAllResult.Data != null && list.GetAllResult.Data.Count > 0)
			{
                EmployeeDto resultDto = list.GetAllResult.Data[0];
                EmployeeMapper modelMapper = new EmployeeMapper();

                resultModel = modelMapper.Mapping(resultDto);

                //Test
                resultModel.BirthDate = resultModel.BirthDate.AddYears(543);
			}

            return View(resultModel);
		}

        public ActionResult Update(EmployeeModel inputModel)
		{
            if (ModelState.IsValid)
            {
                EmployeeService.EmployeeServiceClient service = new EmployeeService.EmployeeServiceClient();
                UpdateRequest objUpdate = new UpdateRequest(new EmployeeDto
                {
                    Address = inputModel.Address,
                    EmpId = inputModel.EmpId,
                    Id = inputModel.Id,
                    JobTitle = inputModel.JobTitle,
                    MarriedStatus = inputModel.MarriedStatus,
                    Name = inputModel.Name,
                    Status = inputModel.Status,
                    Surname = inputModel.Surname,
                    Title = inputModel.Title,
                    BirthDate = inputModel.BirthDate,
                });

                service.Update(objUpdate);
                return RedirectToAction("ListEmployee", "Employee");
            }
            else
            {
                return View("ViewDetail");
            }
			
		}

        public ActionResult Add()
        {
            return View("AddEmployee");
        }

        [HttpPost]
        public ActionResult Add(EmployeeModel inputModel)
        {
            if (ModelState.IsValid)
            {
                EmployeeService.EmployeeServiceClient service = new EmployeeService.EmployeeServiceClient();

                AddRequest objAdd = new AddRequest(new EmployeeDto
                {
                    Address = inputModel.Address,
                    EmpId = inputModel.EmpId,
                    JobTitle = inputModel.JobTitle,
                    MarriedStatus = inputModel.MarriedStatus,
                    Name = inputModel.Name,
                    Status = inputModel.Status,
                    Surname = inputModel.Surname,
                    Title = inputModel.Title,
                    BirthDate = inputModel.BirthDate
                });

                service.Add(objAdd);
                return RedirectToAction("ListEmployee");
            }
            else
            {
                return View("AddEmployee");
            }
           
        }

        [HttpPost]
        public ActionResult DeleteEmployees(string[] checkbox)
        {
            ListEmployeeModel input = new ListEmployeeModel();
            if (ModelState.IsValid)
            {
                input = Delete(checkbox, input);
            }

            SetupRegisterViewModel(input);
            return View("ListEmployee", input);
        }

        [HttpPost]
        public String DeleteEmployeeById(string Id)
        {
            List<string> delList = new List<string>();
            delList.Add(Id);
            EmployeeService.EmployeeServiceClient service = new EmployeeService.EmployeeServiceClient();
            service.Delete(new DeleteRequest(delList));

			
			return "Success";

            //return RedirectToAction("ListEmployee");
        }

        // Check does empId exist
        [HttpPost]
        public JsonResult doesEmpIdExist(string EmpId, string Mode, string OldValue)
        {
            bool callCheck = false;
            if (Mode.Equals("Add", StringComparison.OrdinalIgnoreCase))
            {
                callCheck = true;
            }
            else if (Mode.Equals("Edit", StringComparison.OrdinalIgnoreCase))
            {
                if (!OldValue.Equals(EmpId, StringComparison.OrdinalIgnoreCase))
                    callCheck = true;
            }

            if (callCheck)
            {
                GetAllResponseModel temp = Search(new GetAllRequestModel()
                {
                    EmpId = EmpId,
                    Name = "",
                    Status = 0,
                    Sort = "EmpId",
                    SortType = sType.ASC
                });
                return Json(temp.EmpList.Count == 0);
            }
            else
                return Json(true);
        }

        private void SetupRegisterViewModel(ListEmployeeModel model)
        {
            model.BindingStatus = new SelectList(EmployeeMapper.GetEmployeeStatusForDDL(), "StatusId", "StatusName");
        }

        private ListEmployeeModel Delete(string[] inputList, ListEmployeeModel input)
        {
            List<string> delList = new List<string>();
            if (inputList != null && inputList.Length > 0)
            {
                foreach (string id in inputList)
                {
                    delList.Add(id);
                }
                EmployeeService.EmployeeServiceClient service = new EmployeeService.EmployeeServiceClient();
                DeleteResponse resEmp = service.Delete(new DeleteRequest(delList));
            }

            input.ListOfEmployee = PrepareSearch(input);
            return input;
        }

        private List<EmployeeModel> PrepareSearch(ListEmployeeModel input)
        {

            GetAllRequestModel searchInputs = new GetAllRequestModel()
            {
                EmpId = (input.EmpIdSearch == null) ? "" : input.EmpIdSearch,
                Name = (input.NameSearch == null) ? "" : input.NameSearch,
                Status = (input.StatusSearch == 0) ? 0 : input.StatusSearch,
                Sort = "EmpId", SortType = sType.ASC
            };
            GetAllResponseModel result = Search(searchInputs);
            return result.EmpList;
        }

        private GetAllResponseModel Search(GetAllRequestModel input)
        {
            EmployeeServiceClient service = new EmployeeServiceClient();
            GetAllRequest gAllreq = new GetAllRequest(new GetAllRequestDto { 
                 EmpId = input.EmpId,
                 Name = input.Name, 
                 Sort = input.Sort, 
                 SortType = input.SortType.ToString(),
                 Status = input.Status
            });
            GetAllResponse response = service.GetAll(gAllreq);
            GetAllResponseModel result = new GetAllResponseModel();
            result.EmpList = new List<EmployeeModel>();
            if(response != null)
            {
                if (response.GetAllResult.Data != null && response.GetAllResult.Data.Count > 0)
                {
                    foreach (EmployeeDto responseDTO in response.GetAllResult.Data)
                    {
                        EmployeeModel resultModel = null;
                        EmployeeDto tempDto = responseDTO;
                        EmployeeMapper modelMapper = new EmployeeMapper();
                        resultModel = modelMapper.Mapping(tempDto);
                        result.EmpList.Add(resultModel);
                    }
                }
            }
            return result;
        }
    }
}
